//TCP通信的服务端

#include<stdio.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>

int main(){

    //1、创建用于监听的套接字。参数一表示采用IpV4，参数二表示采用流式协议，参数三0表示TCP通信
    int lfd = socket(AF_INET, SOCK_STREAM, 0);
    if(lfd == -1){
        perror("socket");
        exit(-1);
    }

    //2、绑定套接字
    struct sockaddr_in saddr;
    saddr.sin_family = AF_INET;
    //inet_pton将主机字节序转换成网络字节序，并保存在saddr.sin_addr.s_addr中
    inet_pton(AF_INET, "127.0.0.1", &saddr.sin_addr.s_addr);
    //或者 saddr.sin_addr.s_addr = INADDR_ANY; 表示任意网卡都监听
    //htons将主机字节序转换成网路short类型
    saddr.sin_port = htons(9999);
    int ret = bind(lfd, (struct sockaddr*)&saddr,sizeof(saddr));
    if(ret == -1){
        perror("bind");
        exit(-1);
    }

    //3、监听
    ret = listen(lfd, 8);
    if(ret == -1){
        perror("listen");
        exit(-1);
    }

    //4、接收客户端连接
    struct sockaddr_in clientaddr;                //用于保存客户端的sockaddr信息
    int len = sizeof(clientaddr);
    //accept函数用于接收客户端的连接，并获得一个接收的文件描述符cfd
    int cfd = accept(lfd, (struct sockaddr *)&clientaddr, &len);
    if(cfd == -1){
        perror("accept");
        exit(-1);
    }

    //输出客户端的信息
    char clientIP[16];
    inet_ntop(AF_INET,&clientaddr.sin_addr.s_addr,clientIP,sizeof(clientIP));
    unsigned short clientPort = ntohs(clientaddr.sin_port);
    printf("client ip: %s, client port: %d\n",clientIP,clientPort);

    //5、通信过程
    char recvBUf[1024] = {0};
    while(1){
        //获取客户端的数据
        int datalen = read(cfd, recvBUf, sizeof(recvBUf));
        if(datalen == -1){
            perror("read");
            exit(-1);
        } else if(datalen > 0){
            printf("Receive client data: %s\n",recvBUf);
        } else if(datalen == 0){
            printf("client closed...\n");
            break;
        }
        //给客户端发送数据
        char* data = "hello, I am sercver!";
        write(cfd, data, strlen(data));
    }
    

    //6、关闭文件描述符
    close(cfd);
    close(lfd);

    return 0;
}